/**
 * @Title: InsertOrUpdateSyncLogic.java
 * @Package: com.jason.fingerprint.logic
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月2日06:48:59
 * @Version: V1.0
 */
package com.jason.fingerprint.logic;

import java.util.ArrayList;
import java.util.List;

import org.kymjs.aframe.http.HttpCallBack;
import org.kymjs.aframe.http.KJFileParams;
import org.kymjs.aframe.http.KJHttp;
import org.kymjs.aframe.utils.StringUtils;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android_serialport_api.FingerprintManager;
import android_serialport_api.FingerprintReader;
import android_serialport_api.FingerprintReader.OnDownCharListener;
import android_serialport_api.FingerprintReader.OnStoreCharListener;

import com.google.gson.GsonBuilder;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.AppGlobal;
import com.jason.fingerprint.beans.InsertOrUpdateRecordResp;
import com.jason.fingerprint.beans.RecordBean;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.configs.HttpConfig;
import com.jason.fingerprint.utils.CodecUtils;

/**
 * @ClassName: InsertOrUpdateSyncLogic
 * @Description: 指纹录入或者修改
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月2日06:49:03
 */
public class InsertOrUpdateSyncLogic extends Logic {

	private static final String TAG = "InsertOrUpdateSyncLogic";

	private Handler mHandler;
	private boolean mIsCallBack = false;// 是否有回调，此需要Handle,默认不回调
	private Message mMessage;
	private RecordBean mRecordBean;
	private int mState;// 操作类型 0代表新增,1代表修改
	private FingerprintReader mAsyncFingerprint;
	private List<FingerPrintBean> mFingerPrintBeans;

	private int mFingerId = 0;
	private int mFingerCount = 0;
	private int mFingerCurrent = -1;

	public InsertOrUpdateSyncLogic(AppContext appContext, Handler handler,
			boolean isCallBack, RecordBean recordBean) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
		this.mIsCallBack = isCallBack;
		this.mRecordBean = recordBean;
	}

	@Override
	public void execute() {
		initAsyncFingerprint();
		datbRecordSync();
	}

	private void initAsyncFingerprint() {
		mAsyncFingerprint = FingerprintManager.getInstance().getNewAsyncFingerprint();
		mAsyncFingerprint.setOnDownCharListener(new OnDownCharListener() {

			@Override
			public void onDownCharSuccess() {
				mAsyncFingerprint.PS_StoreChar(2, mFingerId);
			}

			@Override
			public void onDownCharFail() {
				storeFinger();
			}
		});
		//mAsyncFingerprint.PS_DeleteChar(mFingerId, 1);
		mAsyncFingerprint.setOnStoreCharListener(new OnStoreCharListener() {

			@Override
			public void onStoreCharSuccess() {
				storeFinger();
			}

			@Override
			public void onStoreCharFail() {
				storeFinger();
			}
		});
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jason.fingerprint.logic.Logic#send()
	 */
	@Override
	public void send() {
		if (mIsCallBack) {
			mHandler.sendMessage(mMessage);
			mMessage = new Message();
		}
	}

	private void datbRecordSync() {
		mParams = new KJFileParams();
		initParams();
		mParams.put(AppGlobal.HTTP_PARAM_IMEI, mImei);
		String url = HttpConfig.POST_URL_ELECTRICANDFINGERPRINT_INSERTORUPDATE;
		Log.i(TAG, "----->API:" + url);
		Log.i(TAG, "----->Param:" + mParams.getParamString());
		KJHttp kjHttp = new KJHttp();
		kjHttp.post(url, mParams, new HttpCallBack() {

			@Override
			public void onSuccess(Object arg0) {
				try {
					Log.i(TAG, "----->arg0:" + arg0);
					String result = CodecUtils.base64Decode(arg0.toString());
					Log.i(TAG, "----->Result:" + result);
					InsertOrUpdateRecordResp baseBean = new GsonBuilder()
							.create().fromJson(result,
									InsertOrUpdateRecordResp.class);
					if (baseBean.isNotEmpty()) {
						mMessage.obj = baseBean.getRespMsg();
						mMessage.what = 0;
						send();
						// TODO 需要把此指纹信息录入到设备中
						String id = baseBean.getValues().get(0);
						Log.i(TAG, "----->mState:" + mState);
						Log.i(TAG, "----->id:" + id);
						if (mState == 0) {// 新添
							if (!StringUtils.isEmpty(id)) {
								mRecordBean.setElectronicsId(id);
								String userId = id;
								String userName = mRecordBean.getName();
								String fp1 = mRecordBean.getFp_1();
								String fp2 = mRecordBean.getFp_2();
								String cardNo = mRecordBean.getCardNO();
								if (StringUtils.isEmpty(fp1)
										&& StringUtils.isEmpty(fp2)) {
									mRecordBean.setIsEntry(0);
								} else {
									mRecordBean.setIsEntry(1);
								}
								mKjdb.save(mRecordBean);
								// 保存工作人员指纹信息
								mKjdb.save(new FingerPrintBean(userId,
										userName, fp1,cardNo, 1, 1));
								mKjdb.save(new FingerPrintBean(userId,
										userName, fp2,cardNo, 1, 2));
							}

						} else if(mState == 1) {
							mKjdb.update(mRecordBean);
						}
						Log.i(TAG, "---000-->mRecordBean:" + id);
						Log.i(TAG, "---222-->mRecordBean:" + mRecordBean);
						// 更新finger
						updateFingerInfo();
					} else {
						mMessage.what = 1;
						mMessage.obj = baseBean.getRespMsg();
						send();
					}
				} catch (Exception e) {
					mMessage.what = 1;
					mMessage.obj = "服务器错误";
					send();
				}
			}

			@Override
			public void onLoading(long arg0, long arg1) {
				Log.i(TAG, "----->Result:arg0:" + arg0 + ",arg1:" + arg1);
			}

			@Override
			public void onFailure(Throwable arg0, int arg1, String arg2) {
				Log.i(TAG, "----->Result:arg1:" + arg1 + ",arg2:" + arg2);
				mMessage.what = 1;
				mMessage.obj = "服务器错误";
				send();
			}
		});
	}

	// 储存指纹信息到设备
	private synchronized void storeFinger() {
		if (mAsyncFingerprint != null) {
			mFingerCurrent++;
			FingerPrintBean bean = null;
			if (mFingerCurrent > -1 && mFingerCurrent < mFingerCount) {
				bean = mFingerPrintBeans.get(mFingerCurrent);
				if (bean != null && !StringUtils.isEmpty(bean.getFp())) {
					Log.i(TAG, "---666--> storeFinger bean:" + bean);
					mFingerId = bean.getId();
					Log.i(TAG, "---777--> storeFinger mFingerId:" + mFingerId);
					byte[] b = CodecUtils
							.base64DecodeToByte(bean.getFp());
					if (b != null) {
						mAsyncFingerprint.PS_DownChar(b);
					}else {
						storeFinger();
					}
				} else {
					storeFinger();
				}
			} 
		}
	}
	
	private int mUpdateCurrent = 1;

	private synchronized void updateFingerInfo() {
		if (mUpdateCurrent > 2) {
			return;
		}
		if (mUpdateCurrent == 1) {
			mFingerPrintBeans = new ArrayList<FingerPrintBean>();
		}
		int state = mUpdateCurrent;
		try {
			String where = "userId = '" + mRecordBean.getElectronicsId()
					+ "' and type = 1 and state = " + state;
			Log.i(TAG, "---333--> updateFingerInfo where:" + where);
			List<FingerPrintBean> beans = mKjdb.findAllByWhere(
					FingerPrintBean.class,
					where);
			if (beans != null && !beans.isEmpty()) {
				FingerPrintBean bean = beans.get(0);
				Log.i(TAG, "---111--> updateFingerInfo bean:" + bean);
				if (bean != null) {
					bean.setCardNo(mRecordBean.getCardNO());
					if (state == 1) {
						bean.setFp(mRecordBean.getFp_1());
					} else if (state == 2) {
						bean.setFp(mRecordBean.getFp_2());
					}
					Log.i(TAG, "---444--> updateFingerInfo bean:" + bean);
					mKjdb.update(bean);
					mFingerPrintBeans.add(bean);
				}
			}
			if (state == 2) {
				Log.i(TAG, "---555--> updateFingerInfo bean:");
				if (mFingerPrintBeans != null
						&& !mFingerPrintBeans.isEmpty()) {
					mFingerCount = mFingerPrintBeans.size();
					Log.i(TAG, "---555--> updateFingerInfo mFingerCount:" + mFingerCount);
					storeFinger();
				}
			}
		} catch (Exception e) {
			Log.i(TAG, e.getMessage());
		}
		mUpdateCurrent ++;
		updateFingerInfo();
	}

	private void initParams() {
		if (mRecordBean == null) {
			mMessage.what = 1;
			send();
			return;
		} else {
			Log.i(TAG, mRecordBean.toString());
			if (!StringUtils.isEmpty(mRecordBean.getType())) {
				mState = Integer.valueOf(mRecordBean.getType());
				mParams.put("type", mRecordBean.getType());
			}
			if (!StringUtils.isEmpty(mRecordBean.getName())) {
				mParams.put("name", mRecordBean.getName());
			}
			if (!StringUtils.isEmpty(mRecordBean.getElectronicsId())) {
				mParams.put("rymcId", mRecordBean.getElectronicsId());
			}
			if (!StringUtils.isEmpty(mRecordBean.getTelephone())) {
				mParams.put("telephone", mRecordBean.getTelephone());
			}
			if (!StringUtils.isEmpty(mRecordBean.getIdentityNO())) {
				mParams.put("identityNO", mRecordBean.getIdentityNO());
			}
			if (!StringUtils.isEmpty(mRecordBean.getCardNO())) {
				mParams.put("cardNO", mRecordBean.getCardNO());
			}
			if (!StringUtils.isEmpty(mRecordBean.getRegisteredId())) {
				mParams.put("organId", mRecordBean.getRegisteredId());
			}
			if (!StringUtils.isEmpty(mRecordBean.getRegistered())) {
				mParams.put("organ", mRecordBean.getRegistered());
			}
			if (!StringUtils.isEmpty(mRecordBean.getFp_1())) {
				mParams.put("fp_1", mRecordBean.getFp_1());
			}
			if (!StringUtils.isEmpty(mRecordBean.getFp_2())) {
				mParams.put("fp_2", mRecordBean.getFp_2());
			}
		}

	}

	/* (non-Javadoc)
	 * @see com.jason.fingerprint.logic.Logic#destory()
	 */
	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}

}
